/*
The MIT License (MIT)
Copyright (c) 2013 Dalvik Boss dalvikboss@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package sidl.generator.java;

import sidl.generator.GeneratorContext;

public class ThreadedServiceGenerator extends JavaGeneraor {

    public ThreadedServiceGenerator(GeneratorContext context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void doGenerateJava() throws Throwable {
        println("abstract class ThreadedService extends Service {");
        println("    boolean done = false;");
        if(doc.isAndroidIpc()) {
            println("    android.net.LocalServerSocket ss;");    
            println("    public ThreadLocal<Integer> pid = new ThreadLocal<Integer>() {");
            println("        @Override");
            println("        protected Integer initialValue() {");
            println("            return -1;");
            println("        }");
            println("    };");                
            
            println("    public ThreadLocal<Integer> uid = new ThreadLocal<Integer>() {");
            println("        @Override");
            println("        protected Integer initialValue() {");
            println("            return -1;");
            println("        }");
            println("    };");
            
        } else {
            println("    ServerSocket ss;");    
        }
        
        
        println("");
        
        println("");
        if(doc.isAndroidIpc()) {
            println("    private String name;");
            println("    public ThreadedService(String name) {");
            println("        this.name = name;");
            println("    }");
        } else {
            println("    private int port;");
            println("    public ThreadedService(int port) {");
            println("        this.port = port;");
            println("    }");            
        }


        println("    public void start() throws SidlException {");
        println("        try {");
        if(doc.isAndroidIpc()) {
            println("            ss = new android.net.LocalServerSocket(name);");
        } else {
            println("            ss = new ServerSocket(port);");    
        }
        
        println("            new Thread(this).start();");
        println("        } catch (Throwable t) {");
        println("            throw new SidlException(t);");
        println("        }");
        println("");
        println("    }");
        println("");
        println("    public void run() {");
        println("        while (!done) {");
        println("            try {");
        if(doc.isAndroidIpc()) {
            println("                android.net.LocalSocket s = ss.accept();");
        } else {
            println("                Socket s = ss.accept();");    
        }
        
        println("                ThreadedServiceTask task = new ThreadedServiceTask(s);");
        println("            }catch(SocketTimeoutException ste) {");
        println("            }catch(Throwable t) {");
        println("            }");
        println("        }");
        println("        try {");
        println("            ss.close();");
        println("        }catch(Throwable t) {");
        println("        }");
        println("    }");
        println("");
        println("    private class ThreadedServiceTask extends IoHelper.BlockingIo implements Runnable {");
        
        if(doc.isAndroidIpc()) {
            println("        private android.net.LocalSocket s;");
            println("        public ThreadedServiceTask(android.net.LocalSocket s) {");
            println("            this.s = s;");
            println("            new Thread(this).start();");
            println("        }");
            
        } else {
            println("        private Socket s;");
            println("        public ThreadedServiceTask(Socket s) {");
            println("            this.s = s;");
            println("            new Thread(this).start();");
            println("        }");
            
        }


        println("        //@Override");
        println("        public void run() {");
        if(doc.isAndroidIpc()) {
            println("            try {");
            println("                pid.set(s.getPeerCredentials().getPid());");
            println("            }catch(Throwable t) {");
            println("                t.printStackTrace();");
            println("            }");
            println("            try {");
            println("                uid.set(s.getPeerCredentials().getUid());");
            println("            }catch(Throwable t) {");
            println("                t.printStackTrace();");
            println("            }");
            
        }
        println("            try {");

        println("                IoHelper.ObjectReader or = new IoHelper.ObjectReader();");
        println("                recv(or.bb);");
        println("                long low = or.get_long();");
        println("                long high = or.get_long();");
        println("                AgentID aid = new AgentID(low, high);");
        println("                int mode = or.get_int();");
        println("                if(mode==IoHelper.IO_INVOKE) {");
        println("                    IoHelper.ObjectWriter ow = new IoHelper.InvokeDispatcher().dispatch(or, ThreadedService.this);");
        println("                    send(ow.bb);");
        println("                } else {");
        println("                    throw new SidlException(\"only invoke mode supported in threaded service \" + mode);");
        println("                }");
        

        println("            } catch (Throwable t) {");
        println("                t.printStackTrace();");
        println("            }");
        println("            try {");
        println("                s.close();");
        println("            } catch (IOException e) {");
        println("                // TODO Auto-generated catch block");
        println("                e.printStackTrace();");
        println("            }");
        println("        }");
        println("");
        println("        @Override");
        println("        OutputStream os() throws SidlException {");
        println("            try {");
        println("                return s.getOutputStream();");
        println("            }catch(Throwable t) {");
        println("                throw new SidlException(t);");
        println("            }");
        println("        }");
        println("");
        println("        @Override");
        println("        InputStream is() throws SidlException {");
        println("            try {");
        println("                return s.getInputStream();");
        println("            }catch(Throwable t) {");
        println("                throw new SidlException(t);");
        println("            }");
        println("        }");
        println("");
        println("    }");
        println("");
        println("}");
        

    }

}
